var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3001;
const Redis = require("./tools/redis");
// import Socket from './tools/Socket';
const Socket = require('./tools/Socket');
const login = require("./src/login");
const api = require("./data/api");
// var port = normalizePort(process.env.PORT || 3002); 
// var https_port = normalizePort(process.env.HTTPS_PORT || 443); //https证书 var opts = { key: fs.readFileSync('pem/openssl/ssl.key'), cert: fs.readFileSync('pem/openssl/ssl.crt') }; var server = http.createServer(handler); var httpsServer = https.createServer(opts, function(req, res) { res.writeHead(200, { "Content-Type": "text/plain" }); res.write("hello https"); res.end(); }); server.listen(port); httpsServer.listen(https_port); server.on('error', onError); server.on('listening', onListening); httpsServer.on('error', onError); httpsServer.on('listening', onListening); //socket.io var io = require('socket.io')({}); <-------- 这里改如何设置 io.attach(server); io.attach(httpsServer);
function result(code = 404, msg = "非法请求", data = {}) {
    return {
        code, data, msg
    };
}
app.get('/setData', (req, res) => __awaiter(this, void 0, void 0, function* () {
    let userinfo = {
        username: 'zhangsan',
        age: '20'
    };
    let ress = yield Redis.setData("user", userinfo);
    res.json(ress);
}));
app.get('/getData', function (req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        let key = 12;
        let data = yield Redis.getData(key);
        res.json(data);
    });
});
app.get('/get', function (req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        let data = yield Redis.hGet("test1");
        res.json(data);
    });
});
app.get('/set', function (req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        let key = req.query.key;
        let val = req.query.val;
        let data = yield Redis.hSet("test1", key, val);
        res.json(data);
    });
});
app.get('/del', function (req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        let key = req.query.key;
        let data = yield Redis.hDel("test1", key);
        res.json(data);
    });
});
io.on('connection', (socket) => __awaiter(this, void 0, void 0, function* () {
    console.log('新加入一个连接。');
    // socket.emit('message', "dengk");
    socket.on('setRoom', (data) => __awaiter(this, void 0, void 0, function* () {
        console.log(123213);
        let res = yield login.login(data, socket.id);
        console.log(res);
        if (res.code == 400) {
            socket.emit("login", res);
            socket.disconnect();
        }
        else if (res.code == 300) {
            io.to(res.data).emit("login", res);
        }
        else {
            io.emit("getList", {
                code: 200,
                data: {},
                msg: "有用户连接"
            });
        }
    }));
    socket.on('chat message', function (data) {
        var toName = data.to;
        var toId = data.id;
        const hashName = {};
        // if (toId = hashName[toName]) {
        //   var toSocket = _.findWhere(io.sockets.sockets, { id: toId });
        // //   socket.broadcast.emit("a123", data.msg) 
        //   toSocket.emit('message', data.msg);
        // }
    });
    // 当关闭连接后触发 disconnect 事件
    socket.on('disconnect', (data) => __awaiter(this, void 0, void 0, function* () {
        // login.delLoginInfo(socket.id)
        io.emit("getList", {
            code: 200,
            data: {},
            msg: "有用户断开"
        });
    }));
}));
app.get('/wordcloud', (req, res) => __awaiter(this, void 0, void 0, function* () {
    io.emit("wordcloud", {
        type: req.query.type,
        data: req.query.data
    });
    let data = result(200, "发送成功", []);
    res.json(data);
}));
app.get('/resolve', (req, res) => __awaiter(this, void 0, void 0, function* () {
    let room = req.query.room;
    let type = req.query.type || 0;
    let socket_id = yield Redis.hGetValue("tokenList", room);
    let data = {};
    if (socket_id) {
        if (type == 1) {
            data = result(200, "确认登录", req.query.user);
        }
        else {
            data = result(400, "取消登录", {});
        }
        io.to(socket_id).emit("login", data);
        res.json(data);
    }
    else {
        res.json(result(404, "非法请求", {
            sid: socket_id, room
        }));
    }
}));
app.get('/', (req, res) => {
    console.log("首页");
    // let data = api
    // res.json(data)
    // res.sendFile();
    // let socket = new SocketName.Socket()
    let socket = new Socket();
    socket.send();
    res.sendFile(__dirname + '/index.html');
});
//同意登录
//拒绝登录
app.get('/reject', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});
app.get("/getlist", (req, res) => {
    let data = {};
    // data=io.sockets.clients('/'); 
    data = io.sockets.adapter.rooms;
    console.log(io);
    // var clients = io.nsps["/"].sockets;
    res.json(data);
});
app.post('/send', (req, res) => {
    if (req.headers.token == "msg123") {
        let data = {
            code: 200,
            data: req.query,
            msg: "返回成功"
        };
        io.emit('chat message', data);
        res.json(data);
    }
    else {
        res.json({
            code: 404,
            data: [],
            msg: "token错误"
        });
    }
});
http.listen(port, () => {
    console.log(`Socket.IO server running at http://localhost:${port}/`);
});
